<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { $t } from '@/locales';
import { usePersistentCountdown } from '@/hooks/business/use-persistent-countdown';
import { fetchCaptcha } from '@/service/api/comm';
import { REG_CODE_FOUR } from '@/constants/reg';

const authStore = useAuthStore();
const { routerPush, toLogin } = useRouterPush();
const { formRef, validate } = useNaiveForm();
const route = useRoute();

interface FormModel {
  account: string;
  password: string;
  agreedToTerms: boolean;
  captcha_id: string;
  captcha_code: string;
}

const model: FormModel = reactive({
  account: (route.query.email as string) || 'string',
  password: 'string',
  agreedToTerms: false,
  captcha_id: '',
  captcha_code: ''
});
const isVerificationMode = ref(false);

const rules = computed(() => {
  const { formRules, createRequiredRule } = useFormRules();
  return {
    account: isVerificationMode.value ? formRules.codeAccount : formRules.account,
    password: formRules.pwd,
    verificationCode: formRules.verificationCode,
    verificationId: [],
    captcha_code: [
      createRequiredRule($t('form.code.required')),
      {
        pattern: REG_CODE_FOUR,
        message: $t('form.code.invalid'),
        trigger: 'change'
      }
    ],
    agreedToTerms: {
      type: 'boolean',
      required: true,
      validator: (rule: any, value: boolean) => {
        if (!value) {
          return new Error($t('page.login.common.agreeToTermsError'));
        }
        return true;
      },
      trigger: ['change', 'blur']
    }
  };
});

async function handleSubmit() {
  await validate();
  const loginParams = {
    account: model.account,
    provider: 'password',
    password: model.password,
    code: null,
    captcha_id: model.captcha_id,
    captcha_code: model.captcha_code
  };
  await authStore.login(loginParams);
}

function toggleVerificationMode() {
  isVerificationMode.value = !isVerificationMode.value;
  // 手动触发规则验证
  formRef.value?.validate();
}

// 使用新的持久化倒计时 Hook
const { countdown, startCountdown } = usePersistentCountdown('login-verification-code');

function handleSendVerificationCode() {
  if (countdown.value > 0) return;
  // 发送验证码
  // authStore.sendVerificationCode(model.userName)
  startCountdown();
}

const captchaImage = ref('');

async function getCaptcha() {
  try {
    const { data } = await fetchCaptcha(1);
    model.captcha_id = data.captcha_id;
    captchaImage.value = data.captcha_image;
  } catch (error) {
    console.error('Failed to fetch captcha:', error);
  }
}

onMounted(() => {
  getCaptcha();
  if (route.query.focus === 'password') {
    nextTick(() => {
      const formEl = (formRef.value as unknown as { $el: HTMLElement }).$el;
      if (formEl) {
        const passwordInput = formEl.querySelector('input[type="password"]') as HTMLInputElement;
        if (passwordInput) {
          passwordInput.focus();
        }
      }
    });
  }
});
function goToResetPassword() {
  routerPush({
    name: 'reset-password',
    query: { email: model.account }
  });
}
const accountPlaceholder = computed(() => {
  return isVerificationMode.value
    ? $t('page.login.common.codeAccountPlaceholder')
    : $t('page.login.common.accountPlaceholder');
});
</script>

<template>
  <div class="overflow-hidden rounded-lg bg-white shadow-2xl lg:w-460px dark:bg-gray-800 dark:shadow-gray-900/30">
    <div class="p-4 lg:p-8">
      <!-- 头部 Logo 和欢迎文字 -->
      <div class="mb-4 text-center lg:mb-6">
        <img src="" alt="Company Logo" class="mx-auto mb-3 h-10 w-auto lg:mb-4 lg:h-12" />
        <h2 class="text-xl text-gray-900 font-bold lg:text-2xl dark:text-white">
          {{ $t('page.login.login.title') }}
        </h2>
        <p class="mt-1 text-sm text-gray-600 lg:mt-2 dark:text-gray-400">
          {{ $t('page.login.login.subtitle') }}
        </p>
      </div>

      <!-- 表单部分 -->
      <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
        <NFormItem path="account">
          <NInput v-model:value="model.account" :placeholder="accountPlaceholder" />
        </NFormItem>

        <NFormItem v-if="!isVerificationMode" path="password">
          <NInput
            v-model:value="model.password"
            type="password"
            show-password-on="click"
            :placeholder="$t('page.login.common.passwordPlaceholder')"
          />
        </NFormItem>

        <!-- Add captcha section -->
        <NFormItem v-if="!isVerificationMode" class="space-y-2">
          <div class="w-full flex items-center justify-between space-x-2">
            <NInput
              v-model:value="model.captcha_code"
              :placeholder="$t('page.login.common.captchaPlaceholder')"
              class="flex-1"
            />
            <div class="cursor-pointer" @click="getCaptcha">
              <img v-if="captchaImage" :src="'data:image/gif;base64,' + captchaImage" alt="captcha" class="h-13" />
            </div>
          </div>
        </NFormItem>

        <NFormItem v-else class="flex-1">
          <NInput
            v-model:value="model.captcha_code"
            :placeholder="$t('page.login.common.codePlaceholder')"
            path="verificationCode"
          />
          <NButton
            type="primary"
            class="ml-2 min-w-[100px] whitespace-nowrap"
            :disabled="countdown > 0"
            @click="handleSendVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}s` : $t('page.login.common.getCode') }}
          </NButton>
        </NFormItem>

        <!-- 协议和忘记密码 -->
        <div class="mb-4 flex flex-col items-start justify-between lg:flex-row lg:items-center space-y-2 lg:space-y-0">
          <div class="flex flex-wrap items-center">
            <NCheckbox v-model:checked="model.agreedToTerms">
              <span class="text-sm">{{ $t('page.login.common.agreeToTerms') }}</span>
            </NCheckbox>
            <NButton text class="ml-1 text-sm text-blue-600 underline">{{ $t('page.login.common.termsLink') }}</NButton>
          </div>
          <div class="flex items-center">
            <NButton text type="primary" class="text-sm font-medium hover:underline" @click="goToResetPassword">
              {{ $t('page.login.login.forgetPassword') }}
            </NButton>
          </div>
        </div>

        <!-- 栅格 -->
        <div class="flex items-center justify-between lg:grid lg:grid-cols-5 lg:gap-2">
          <NButton
            type="primary"
            size="large"
            block
            :loading="authStore.loginLoading"
            class="lg:col-span-3"
            @click="handleSubmit"
          >
            {{ $t('page.login.login.loginText') }}
          </NButton>
          <NButton size="large" block class="lg:col-span-2" @click="toLogin('register')">
            {{ $t('page.login.register.title') }}
          </NButton>
        </div>

        <!-- 分隔线 -->
        <div class="my-4 flex items-center justify-center">
          <div class="h-[1px] w-full bg-gray-200 dark:bg-gray-700"></div>
          <span class="mx-4 text-sm text-gray-400 dark:text-gray-500">{{ $t('page.login.login.or') }}</span>
          <div class="h-[1px] w-full bg-gray-200 dark:bg-gray-700"></div>
        </div>

        <!-- 切换登录方式 -->
        <div class="mt-4 text-center space-x-2">
          <NButton strong secondary text type="primary" class="text-sm lg:text-base" @click="toggleVerificationMode">
            {{
              isVerificationMode ? $t('page.login.login.passwordLogin') : $t('page.login.login.verificationCodeLogin')
            }}
          </NButton>
        </div>
      </NForm>
    </div>
  </div>
</template>

<style scoped></style>
